package com.red.wood.module.evalMol.service.impl;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.inject.internal.Lists;
import com.google.inject.internal.Maps;
import com.red.wood.common.util.CommonUtils;
import com.red.wood.module.eval.model.SingleTask;
import com.red.wood.module.eval.model.TaskAudit;
import com.red.wood.module.eval.service.ApplicationCdnCNameService;
import com.red.wood.module.eval.service.ApplicationCdnNodeService;
import com.red.wood.module.eval.service.ApplicationCdnService;
import com.red.wood.module.eval.service.DictionaryService;
import com.red.wood.module.eval.service.EvalProjectService;
import com.red.wood.module.eval.service.TaskAuditService;
import com.red.wood.module.eval.service.TaskFlowService;
import com.red.wood.module.evalMol.dao.AdoptNotIntDao;
import com.red.wood.module.evalMol.service.AdoptIspService;
import com.red.wood.module.evalMol.service.GbpsMolService;
import com.red.wood.module.evalMol.service.HouseMolService;
import com.red.wood.module.evalMol.service.IcpMolService;
import com.red.wood.module.evalMol.service.MolService;
import com.red.wood.module.evalMol.service.NotAdoptInfoService;
import com.red.wood.module.evalMol.service.ReportMolService;

@Service
@Transactional
public class MolServiceImpl implements MolService{
	
	private static final Log log = LogFactory.getLog(MolServiceImpl.class);
	
	// 评测通过联系人及联系方式
	private static final String EVAL_REPORT_USER = "EVAL_REPORT_USER";
	private static final String EVAL_REPORT_CONTACT = "EVAL_REPORT_CONTACT";

	@Autowired
	private ApplicationCdnService applicationCdnService;
	@Autowired
	private DictionaryService dictionaryService;
	@Autowired
	private TaskAuditService taskAuditService;
	@Autowired
	private TaskFlowService taskFlowService;
	@Autowired
	private EvalProjectService evalProjectService;
	@Autowired
	private NotAdoptInfoService notAdoptInfoService;
	@Autowired
	private ApplicationCdnNodeService applicationCdnNodeService;
	@Autowired
	private ApplicationCdnCNameService applicationCdnCNameService;
	
	@Autowired
	private HouseMolService houseMolService;
	@Autowired
	private GbpsMolService gbpsMolService;
	@Autowired
	private IcpMolService icpMolService;
	@Autowired
	private ReportMolService reportMolService;
	@Autowired
	private AdoptIspService adoptIspService;
	@Autowired
	private AdoptNotIntDao adoptNotIntDao;
	
	
	public void saveMol(int statue, int type, String singleTaskId){
		if(statue == TaskAudit.EVAL_TASTAUDIT_STATUE_NOTADOPT){ // 不通过
			this.getNotDataMol(singleTaskId);
		} else if(statue == TaskAudit.EVAL_TASTAUDIT_STATUE_ADOPT){ // 通过
			if(type ==  SingleTask.EVAL_SINGLETASK_TYPE_ONLYINTER){ // idc业务评测(仅限互联网资源协作)
				this.getYonlyIntDataMol(singleTaskId);
			} else if(type ==  SingleTask.EVAL_SINGLETASK_TYPE_ISP) { // ISP业务评测 
				this.getYispDataMol(singleTaskId);
			} else if(type ==  SingleTask.EVAL_SINGLETASK_TYPE_CDN) { // CDN业务评测
				this.getYcdnDataMol(singleTaskId);
			} else {
				this.getYnotIntDataMol(singleTaskId);
			}
		}
	}
	
	/**
	 * 评测不通过模板数据入库
	 * @param singleTaskId
	 */
	public void getNotDataMol(String singleTaskId) {
		if(StringUtils.isNotBlank(singleTaskId)){
			Map<String,Object> param = new HashMap<String,Object>();
			param.put("singleTaskId", singleTaskId); //评测任务id
			Map<String,Object> data = applicationCdnService.getEntity(param);
			this.addMol(data); // 增加报告模板信息
			
			// 评测不通过项
			List<Map<String, Object>> notAdoptData = evalProjectService.getBySingleTaskIdAndResult(singleTaskId, 2+"");
			// 获取评测不通过原因
			List<Map<String, Object>> flowList = taskFlowService.getBySingleTaskIdAndStatue(singleTaskId, "评测不通过");
			this.addNotAdoptInfo(notAdoptData, flowList, singleTaskId); //评测不通过报告项
		}
	}
	
	private void getYispDataMol(String singleTaskId){
		Map<String,Object> param = new HashMap<String,Object>();
		param.put("singleTaskId", singleTaskId); //评测任务id
		
		Map<String,Object> data = applicationCdnService.getEntity(param);
		this.addMol(data);
		this.addIspMol(data);
	}
	
	private void getYnotIntDataMol(String singleTaskId){
		Map<String, Object> param = new HashMap<>();
		param.put("singleTaskId", singleTaskId); //评测任务id
		Map<String,Object> data = applicationCdnService.getEntity(param);
		
		this.addMol(data);
		this.addNotIntMol(data);
	}
	
	/**
	 * idc业务评测(仅限互联网资源协作) 评测通过报告模板
	 * @param singleTaskId
	 */
	private void getYonlyIntDataMol(String singleTaskId){
		Map<String, Object> param = new HashMap<>();
		param.put("singleTaskId", singleTaskId); //评测任务id
		Map<String,Object> data = applicationCdnService.getEntity(param);
		
		this.addMol(data);
		this.getNodeData(singleTaskId, CommonUtils.valueOf(data.get("gbps")));
	}
	
	/**
	 * cdn 评测通过报告模板
	 * @param singleTaskId
	 */
	private void getYcdnDataMol(String singleTaskId){
		Map<String, Object> param = new HashMap<>();
		param.put("singleTaskId", singleTaskId); //评测任务id
		Map<String,Object> data = applicationCdnService.getEntity(param);
		
		this.addMol(data);
		this.getNodeData(singleTaskId, CommonUtils.valueOf(data.get("gbps")));
		this.getIcpData(singleTaskId);
	}
	
	/**
	 * isp 通过报告模板
	 * @param data
	 */
	private void addIspMol(Map<String,Object> data){
		String singleTaskId = String.valueOf(data.get("singleTaskId"));
		Map<String, Object> isp = new HashMap<>();
		isp.put("singleTaskId", singleTaskId);
		isp.put("gameProvince", data.get("gameProvince") + "省");
		isp.put("gbps", data.get("gbps") + "Gbps");
		isp.put("gameProvince", data.get("houseName"));
		isp.put("houseAddress", data.get("houseAddress"));
		isp.put("handleInfo", data.get("handleInfo"));
		adoptIspService.delete(singleTaskId);
		adoptIspService.add(isp);
	}

	/**
	 * 不含互联网资源协作
	 * @param data
	 */
	private void addNotIntMol(Map<String,Object> data){
		String singleTaskId = String.valueOf(data.get("singleTaskId"));
		Map<String, Object> notInt = new HashMap<>();
		String provinceAndCity = data.get("gameProvince") + "省" + data.get("gameCity");
		notInt.put("provinceAndCity", provinceAndCity);
		String linkTypeAndGbps = "链路信息（移动/电信/联通）" + data.get("gbps") + "Gbps";
		notInt.put("linkTypeAndGbps", linkTypeAndGbps);
		notInt.put("houseName", data.get("houseName"));
		notInt.put("houseAddress", data.get("houseAddress"));
		notInt.put("handleInfo", data.get("handleInfo"));
		notInt.put("singleTaskId", data.get("singleTaskId"));
		adoptNotIntDao.delete(singleTaskId);
		adoptNotIntDao.add(notInt);
	}
	
	private void addNotAdoptInfo(List<Map<String, Object>> notAdoptData, List<Map<String, Object>> flowList, String singleTaskId){
		List<Map<String, Object>> paramList = Lists.newArrayList();
		Map<String, Object> param = new HashMap<>();
		
		String reason = "";
		if(flowList != null && flowList.size() > 0){
			reason = flowList.get(0).get("reason").toString();
		}
		
		if(notAdoptData != null && notAdoptData.size() > 0){
			for(Map<String, Object> notAdopt : notAdoptData){
				String problem = String.valueOf("[" + notAdopt.get("parentProject")) + "]" + "[" + String.valueOf(notAdopt.get("project")) + "]：" + reason;
				param.put("singleTaskId", singleTaskId);
				param.put("problem", problem);
				paramList.add(param);
			}
		}
		notAdoptInfoService.delete(singleTaskId);
		notAdoptInfoService.addList(paramList);
	}
	
	private void addMol(Map<String,Object> data){
		this.getDefaultPerson(data);
		String singleTaskId = String.valueOf(data.get("singleTaskId"));
		Map<String,Object> paramMap = new HashMap<>();
		paramMap.put("number", String.valueOf(data.get("number")));
		paramMap.put("singleTaskId", singleTaskId);
		paramMap.put("name", String.valueOf(data.get("name")));
		paramMap.put("systemName", String.valueOf(data.get("systemName")));
		paramMap.put("handleDay", String.valueOf(data.get("handleDay")));
		paramMap.put("handleMonth", String.valueOf(data.get("handleMonth")));
		paramMap.put("handleYear", String.valueOf(data.get("handleYear")));
		paramMap.put("deptPerson", String.valueOf(data.get("deptPerson")));
		paramMap.put("personTel", String.valueOf(data.get("personTel")));
		
		reportMolService.delete(singleTaskId);
		reportMolService.add(paramMap);
	}
	
	private void getDefaultPerson(Map<String,Object> data){
		// 获取评测通过信息，责任人和联系方式，及处理时间
		String deptPerson = dictionaryService.getValueByTypeAndKey(EVAL_REPORT_USER, "0");
		if(StringUtils.isBlank(deptPerson)){
			log.error("请检查字典表EVAL_REPORT_USER配置");
		} else {
			data.put("deptPerson", deptPerson);
		}
		String personTel = dictionaryService.getValueByTypeAndKey(EVAL_REPORT_CONTACT, "0");
		if(StringUtils.isBlank(deptPerson)){
			log.error("请检查字典表EVAL_REPORT_CONTACT配置");
		} else {
			data.put("personTel", personTel);
		}
		Map<String, Object> taskAuditMap = taskAuditService.getBySingleTaskId(String.valueOf(data.get("singleTaskId")));
		if(null != taskAuditMap && StringUtils.isNotBlank(taskAuditMap.get("updateTime").toString())){
			Date handleTime = (Date)taskAuditMap.get("updateTime");
			Calendar cal = Calendar.getInstance(); 
			cal.setTime(handleTime);
			data.put("handleDay", cal.get(Calendar.DAY_OF_MONTH));
			data.put("handleMonth", (cal.get(Calendar.MONTH) + 1)+"");
			data.put("handleYear", cal.get(Calendar.YEAR));
		}
	}
	
	/**
	 * 机房、gbps信息
	 * @param singleTaskId
	 * @param gbpsStr
	 */
	private void getNodeData(String singleTaskId, String gbpsStr){
		List<Map<String, Object>> houseList = Lists.newArrayList();
		Map<String, Object> house = new HashMap<>();
		
		List<Map<String, Object>> gbpsList = Lists.newArrayList();
		Map<String, Object> gbps = new HashMap<>();
		
		List<Map<String, Object>> nodeData = applicationCdnNodeService.getBySingleTaskId(singleTaskId);
		if(nodeData != null && nodeData.size() > 0){
			for(Map<String, Object> map : nodeData){
				house.put("singleTaskId", singleTaskId);
				house.put("nodeName", map.get("name"));
				house.put("houseAddr", map.get("address"));
				houseList.add(house);
				
				gbps.put("singleTaskId", singleTaskId);
				gbps.put("province", map.get("province") + "省");
				gbps.put("type", "链路信息（移动/电信/联通）");
				gbps.put("gbps", gbpsStr);
				gbpsList.add(gbps);
			}
		}
		
		houseMolService.delete(singleTaskId);
		houseMolService.addList(houseList);
		
		gbpsMolService.delete(singleTaskId);
		gbpsMolService.addList(gbpsList);
	}

	/**
	 * icp 信息
	 * @param singleTaskId
	 */
	private void getIcpData(String singleTaskId){
		List<Map<String, Object>> icpList = Lists.newArrayList();
		Map<String, Object> icp = Maps.newHashMap();
		
		List<Map<String, Object>> cnameData = applicationCdnCNameService.getBySingleTaskId(singleTaskId);
		if(cnameData != null && cnameData.size() > 0){
			for (Map<String, Object> cname : cnameData) {
				icp.put("domain", cname.get("domain"));
				icp.put("icp", cname.get("icp"));
				icp.put("singleTaskId", cname.get("singleTaskId"));
				icpList.add(icp);
			}
		}
		icpMolService.addList(icpList);
	}
	
}
